$(function() {
  var meetingList = $('#meetingList');
  var dateList = $('#dateList');
  var determineBtn = $('#determineBtn');
  var tabOneLink = $('#tabOneLink');
  var tabTwoLink = $('#tabTwoLink');
  var dateTab = $('#dateTab');
  var useDate = null;
  var meetingDateText = null;

  var meetingArr = [{
    floor: '6',
    id: '3210FD3894A90E25E0532B00A8C04000',
    name: '大会议室',
    projector: true,
    television: false,
    computer: false
  }, {
    floor: '6',
    id: '3210FD3894AA0E25E0532B00A8C04000',
    name: '大培训室',
    projector: true,
    television: false,
    computer: true
  }, {
    floor: '6',
    id: '3210FD3894AB0E25E0532B00A8C04000',
    name: '金融会议室',
    projector: true,
    television: false,
    computer: false
  }, {
    floor: '6',
    id: '3210FD3894AC0E25E0532B00A8C04000',
    name: '金融讨论室',
    projector: false,
    television: false,
    computer: false
  }, {
    floor: '7',
    id: '3210FD3894AD0E25E0532B00A8C04000',
    name: '大会议室',
    projector: true,
    television: false,
    computer: false
  }, {
    floor: '7',
    id: '3210FD3894AE0E25E0532B00A8C04000',
    name: '小会议室(一)',
    projector: false,
    television: false,
    computer: true
  }, {
    floor: '7',
    id: '3210FD3894AF0E25E0532B00A8C04000',
    name: '小会议室(二)',
    projector: false,
    television: false,
    computer: false
  }, {
    floor: '7',
    id: '3210FD3894B00E25E0532B00A8C04000',
    name: '小培训室',
    projector: true,
    television: false,
    computer: false
  }, {
    floor: '8',
    id: '3210FD3894B10E25E0532B00A8C04000',
    name: '大会议室',
    projector: false,
    television: false,
    computer: false
  }, {
    floor: '8',
    id: '3210FD3894B20E25E0532B00A8C04000',
    name: '小会议室',
    projector: true,
    television: false,
    computer: false
  }, {
    floor: '8',
    id: '3210FD3894B40E25E0532B00A8C04000',
    name: '战略会议室',
    projector: false,
    television: false,
    computer: true
  }, {
    floor: '9',
    id: '3210FD3894B50E25E0532B00A8C04000',
    name: '大会议室',
    projector: true,
    television: false,
    computer: false
  }, {
    floor: '9',
    id: '3210FD3894B60E25E0532B00A8C04000',
    name: '小会议室',
    projector: false,
    television: false,
    computer: false
  }, {
    floor: '9',
    id: '3210FD3894B70E25E0532B00A8C04000',
    name: '洽谈室',
    projector: false,
    television: false,
    computer: false
  }];

  $('.content').scroll(function() {
    setTimeout(function() {
      var windowHeight = $('.content').height();
      var scrollTop = $('.content').scrollTop();
      if (scrollTop >= 100) {
        $('#meetingListCont').show();
        $('#meetingList').find('ul').find('li:first').addClass('hidden');
      } else {
        $('#meetingListCont').hide();
        $('#meetingList').find('ul').find('li:first').removeClass('hidden');
      }
    }, 10);
  });

  var newDate = new Date();
  var year = newDate.getFullYear();
  var month = newDate.getMonth() + 1;
  var date = newDate.getDate();
  var day = newDate.getDay();

  setSelectTime()();

  function setSelectTime() {
    var threeDay = 3;
    var weekendFalg = false;
    var timeHtml = '';

    var getTimeList = function() {
      var dateDay = {
        date: newDate.getDate(),
        day: newDate.getDay(),
        month: newDate.getMonth() + 1
      };

      return dateDay;
    };

    var getDayChinese = function(day) {
      var dayChinese = null;
      switch (day) {
        case 0:
          dayChinese = '日';
          break;
        case 1:
          dayChinese = '一';
          break;
        case 2:
          dayChinese = '二';
          break;
        case 3:
          dayChinese = '三';
          break;
        case 4:
          dayChinese = '四';
          break;
        case 5:
          dayChinese = '五';
          break;
        case 6:
          dayChinese = '六';
          break;
      }

      return dayChinese;
    };

    var getValidTime = function(numDate) {
      for (var i = 0; i < 3; i++) {
        var numberDate = 0;
        if (i > 0) {
          numberDate = 1;
        }

        newDate.setDate(getTimeList().date + numberDate);
        if (getTimeList().day == 0) {
          newDate.setDate(getTimeList().date + 1);
        } else if (getTimeList().day == 6) {
          newDate.setDate(getTimeList().date + 2);
        }

        if (i == 0) {
          $('#weekTab').text('周' + getDayChinese(getTimeList().day) + '');
          dateTab.text('' + zerofill(getTimeList().month) + '.' + zerofill(getTimeList().date) + '');
        }

        timeHtml += '<li><span class="week">周' + getDayChinese(getTimeList().day) + '</span>(<span class="date">' + zerofill(getTimeList().month) + '.' + zerofill(getTimeList().date) + '</span>)</li>';
      }

      $('#timeList').empty().append(timeHtml);
    };

    return getValidTime;
  }

  function zerofill(n) {
    return n < 10 ? '0' + n : n;
  }

  $('.tab').on('click', 'li', function() {
    if ($(this).parents('div').is('#tab1')) {
      tabOneLink.removeClass('active');
      $('#weekTab').text($(this).find('.week').text());
      dateTab.text($(this).find('.date').text());
    } else {
      tabTwoLink.removeClass('active');
      $('#floor').text($(this).text());
    }

    initReservedMeeting($.config.mobile, $('#floor').text().replace(/[^0-9]/ig, ''));

    $(this).parents('div').removeClass('active');
  });

  $(document).on('click', function(e) {
    if (!$(e.target).parents().is('.tabs') && !$(e.target).parents().is('.buttons-tab') && !$(e.target).parents().is('.tab-link')) {
      tabOneLink.removeClass('active');
      tabTwoLink.removeClass('active');
      $('.tab').removeClass('active');
    }
  });

  function initMeeting(mobile, storey) {
    var deferred = $.Deferred();
    determineBtn.hide();
    $.ajax({
      url: '/qfang-weixin/qiye/meeting/meetingList',
      data: {
        storey: storey,
        mobile: mobile
      },
      beforeSend: function() {
        $.showPreloader();
      },

      success: function(data) {
        if (data.code == '1000') {
          var items = data.data.items;
          var html = '';
          var headHtml = '';
          var className = '';
          var siestaHtml = '';
          var lastClass = '';
          var itemsLength = items.length;
          switch (itemsLength) {
            case 2:
              className = 'col-50';
              break;
            case 3:
              className = 'col-33';
              break;
            case 4:
              className = 'col-25';
              break;
          }

          $.each(items, function(k, v) {
            if (k == 0) {
              siestaHtml = '<span class="iconfont icon-kafei"></span>';
            } else if (k == 1) {
              siestaHtml = '午';
            } else if (k == 2) {
              siestaHtml = '休';
            } else {
              siestaHtml = '';
            }

            if (k == itemsLength - 1) {
              lastClass = 'last-ul';
            }

            html += '<div class="' + className + '">' +
              '<ul data-name="' + v.name + '" data-id="' + v.id + '" data-floor="' + v.storey + '" class="' + lastClass + '">' +
              '<li class="meeting-name"><span class="names">' + v.name + '</span><span class="number-people">(' + v.number + '人)</span><p class="projector-content"></p></li>' +
              '<li> </li><li> </li><li> </li><li></li><li> </li><li> </li><li> </li><li> </li><li> </li><li> </li>' +
              '</ul>' +
              '</div>';

            headHtml += '<li  class="' + className + '"><span class="names">' + v.name + '</span><span class="number-people">(' + v.number + '人)</span><p class="projector-content"></p></li>'
          });

          meetingList.empty().append(html);
          $('#headMeeting').find('ul').empty().append(headHtml);
          deferred.resolve();
        } else {
          deferred.reject();
        }

      }
    });
    return deferred.promise();
  }

  initReservedMeeting($.config.mobile, $('#floor').text().replace(/[^0-9]/ig, ''));
  var time = ['09', '10', '11', '12', '14', '15', '16', '17', '18', '19', '20'];
  var oneTimeArry = ['9-10', '10-11', '11-12', '午休', '14-15', '15-16', '16-17', '17-18', '18-19', '19-20'];

  function initReservedMeeting(mobile, floor) {
    var d1 = initMeeting(mobile, floor);
    $.when(d1).done(function() {
      var index = dateTab.text().indexOf('.');
      var dayStr = dateTab.text().slice(index + 1);
      var monthStr = dateTab.text().slice(0, 2);
      useDate = '' + year + '-' + monthStr + '-' + dayStr + '';
      meetingDateText = $('#weekTab').text() + '(' + dateTab.text() + ')';
      reservedMeeting(mobile, floor, useDate);
    });
  }

  function reservedMeeting(mobile, floor, date) {
    var uls = meetingList.find('ul');
    $.ajax({
      url: '/qfang-weixin/qiye/meeting/reserveList',
      data: {
        storey: floor,
        date: date,
        mobile: mobile
      },

      success: function(data) {
        $.hidePreloader();
        if (data.code == '1000') {
          var items = data.data.items;
          var selectMark = '<span class="icon icon-check"> </span> <span class="tip icon icon-message"><span class="tip-text">' + floor + '楼大会议室</span></span>';
          var projector = '<span class="remark"><i class="iconfont icon-iconset0225"> </i> </span>';
          var computer = '<span class="remark"><i class="iconfont icon-diannao"> </i> </span>';
          var television = '<span class="remark"><i class="iconfont icon-dianshi"> </i> </span>';
          var firstLiIndex = 0;
          var conferenceIdArry = [];

          if (items.length) {
            $.each(items, function(k, v) {
              $.each(uls, function(n, m) {
                if (v.conferenceId == $(m).data('id')) {

                  var meetingHtml = '<a href="tel:' + v.mobile + '" class="reserved-meeting"><span class="org-name">' + (v.orgName ? v.orgName : '') + '</span><span class="meeting-title">' + (v.title ? v.title : '') + '</span></a>';
                  firstLiIndex = oneTimeArry.indexOf(v.dates.split(',')[0]);

                  var numberFlag = 0;
                  var beforeArray = null;
                  $.each(v.dates.split(','), function(x, z) {
                    var index = v.dates.split(',').indexOf(z);
                    if (z == '11-12') {
                      numberFlag++;
                      beforeArray = v.dates.split(',').slice(0, index + 1);
                    } else if (z == '14-15') {
                      numberFlag++;
                    }
                  });

                  var liIndexArry = [];
                  var aPhone = null;
                  var firstLi = null;
                  $.each(v.dates.split(','), function(x, z) {
                    var index = oneTimeArry.indexOf(z);
                    liIndexArry.push(index);
                    if (index != -1) {
                      if (x == 0) {
                        firstLi = $(m).find('li').eq(index + 1);
                        firstLi.addClass('relative').empty().append(meetingHtml);
                        firstLi.on('click', 'a', function(e) {
                          e.stopPropagation();
                          if ($(this).parents('li').hasClass('expired-time')) {
                            var lastHours = v.dates.split(',')[v.dates.split(',').length - 1].split('-')[1];
                            var nowHours = newDate.getHours();
                            if (nowHours >= lastHours) {
                              $.toast('会议室已过期', 1000);
                            } else {
                              $.toast('正在会议中...', 1000);
                            }

                            return false;
                          }
                        });

                        aPhone = $(m).find('li').eq(index + 1).find('a');
                        aPhone.height(v.dates.split(',').length * 80);
                        var spanOneH = aPhone.find('span').eq(0).height();
                        var spanTwoH = aPhone.find('span').eq(1).height();
                        if (numberFlag == 2) {
                          $(m).find('li').eq(index + 1).find('.reserved-meeting').css({
                            paddingTop: (beforeArray.length * 80 - spanOneH - spanTwoH) / 2
                          });
                        } else {
                          $(m).find('li').eq(index + 1).find('.reserved-meeting').css({
                            paddingTop: (v.dates.split(',').length * 80 - spanOneH - spanTwoH) / 2
                          });
                        }
                      }

                      var reservedLength = $(m).find('a').length;
                      $(m).find('li').eq(index + 1).addClass('js-reserved-time').addClass('reserved-time-' + (n + 1) + '-' + reservedLength);
                    }
                  });
                }
              });
            });

            uls.find('li').not('.meeting-name,.js-reserved-time').addClass('reservations');

          } else {
            uls.find('li').not('.meeting-name').addClass('reservations');
          }

          $.each(uls, function(k, v) {
            $(v).find('li').eq(4).removeClass('reservations');
          });

          uls.find('li.reservations').append(selectMark);

          $.each(uls, function(k, v) {
            var floor = $(v).data('floor');
            var id = $(v).data('id');
            var html = '';

            $.each(meetingArr, function(m, n) {
              if (n.id == id && n.floor == floor) {
                if (n.projector) {
                  html += projector;
                }

                if (n.television) {
                  html += television;
                }

                if (n.computer) {
                  html += computer;
                }

                $(v).find('.projector-content').append(html);
                $('#headMeeting').find('li').eq(k).find('.projector-content').append(html);
              }
            });
          });
        }
      },

      complete: function() {
        $.hidePreloader();
      }
    }).done(function() {
      pollingExpired();
    });
  }

  function pollingExpired() {
    var todayTime = (new Date(useDate)).getTime();
    var newDate = new Date();
    var nowTime = newDate.getHours();
    var allFlag = false;
    if (newDate.getTime() > todayTime) {
      if (nowTime == 13) {
        nowTime = 14;
      } else if (nowTime >= 20) {
        allFlag = true;
      }

      var timeIndex = time.indexOf('' + zerofill(nowTime) + '') + 1;
      var uls = meetingList.find('ul');

      $.each(uls, function(k, v) {
        var liArry = $(v).find('li');
        if (allFlag) {
          $.each(liArry, function(n, m) {
            if (n > 0 && n != 4) {
              $(m).addClass('expired-time');
            }
          });
        } else {
          $.each(liArry, function(n, m) {
            if (n < timeIndex && n > 0 && n != 4) {
              $(m).addClass('expired-time');
            }
          });
        }

      });
    }
  }

  var startIndex = null;
  var endIndex = null;
  var resultArry = null;
  var strFirstIndex = 0;
  var strLastIndex = 0;

  function resetSelf(selfUl) {
    selfUl.removeClass('yes');
    startIndex = null;
    endIndex = null;
    resultArry = [];
    strFirstIndex = 0;
    strLastIndex = 0;
  }

  meetingList.on('click', 'li.reservations', function() {
    var self = $(this);
    if (self.hasClass('expired-time')) {
      $.toast('会议室已过期');
      return;
    }

    var meetingUlSelect = $('#meetingList').find('ul.yes');
    var iconCheck = self.find('.icon-check');
    /* var equipment = self.find('.equipment');*/
    var index = self.index();
    var selfUl = self.parents('ul');
    var selectLiLength = selfUl.find('li.js-select').length;
    var meetingIndexArry = [1, 2, 3, 5, 6, 7, 8, 9, 10];
    var falg = true;
    if (meetingUlSelect.length) {
      if (!selfUl.hasClass('yes')) {
        falg = false;
      }
    }

    if (falg) {

      selfUl.addClass('yes');
      var selectLiLength = selfUl.find('li.js-select').length;

      if (selectLiLength == 0) {
        strFirstIndex = meetingIndexArry.indexOf(index);
        if (strFirstIndex != -1) {
          startIndex = strFirstIndex;
        }
      } else if (selectLiLength == 1) {
        strLastIndex = meetingIndexArry.indexOf(index);
        if (strLastIndex != -1) {
          endIndex = strLastIndex;
        }
      }

      if (selectLiLength >= 2) {
        selfUl.find('li.js-select').find('.icon-check').hide();
        //selfUl.find('li.js-select').find('.equipment').show();
        selfUl.find('li').removeClass('js-select');
        selfUl.removeClass('yes');
        resetSelf(selfUl);
      } else {
        if (startIndex < endIndex || endIndex == null) {
          if (!endIndex) {
            resultArry = meetingIndexArry.slice(startIndex, startIndex + 1);
          } else {
            resultArry = meetingIndexArry.slice(startIndex, endIndex + 1);
          }

        } else {
          resultArry = meetingIndexArry.slice(endIndex, startIndex + 1);
        }

        if (resultArry.length == 1) {
          if (selfUl.find('li').eq(resultArry[0]).hasClass('js-select')) {
            selfUl.find('li').eq(resultArry[0]).find('.icon-check').hide();
            //selfUl.find('li').eq(resultArry[0]).find('.equipment').show();
            selfUl.find('li').eq(resultArry[0]).removeClass('js-select');
            resetSelf(selfUl);
          }
        }

        var falgCross = true;
        $.each(resultArry, function(k, v) {
          var li = selfUl.find('li').eq(v);
          if (li.hasClass('js-reserved-time')) {
            $.toast('不能跨域选择');
            falgCross = false;
            return false;
          }
        });

        if (falgCross) {
          $.each(resultArry, function(k, v) {
            var li = selfUl.find('li').eq(v);

            if (li.hasClass('reservations')) {
              li.addClass('js-select');
              li.find('.icon-check').show();
              //li.find('.equipment').hide();

              var period = null;
              var timePoit = null;

              if (v >= 5) {
                period = $.trim(dateList.find('li').eq(v + 1).text()) + '-' + $.trim(dateList.find('li').eq(v + 2).text());
                timePoit = $.trim(dateList.find('li').eq(v + 1).data('time')) + '-' + $.trim(dateList.find('li').eq(v + 2).data('time'));
              } else {
                period = $.trim(dateList.find('li').eq(v).text()) + '-' + $.trim(dateList.find('li').eq(v + 1).text());
                timePoit = $.trim(dateList.find('li').eq(v).data('time')) + '-' + $.trim(dateList.find('li').eq(v + 1).data('time'));
              }

              li.addClass('js-select').attr('time', period);
              li.addClass('js-select').attr('timePoit', timePoit);
            } else {
              return false;
            }
          });
        }
      }

      if (selfUl.find('li.js-select').length > 0) {
        determineBtn.show();
      } else {
        determineBtn.hide();
      }
    } else {
      $.toast('预定不同会议室请分开预定');
    }

  });

  determineBtn.on('click', function() {
    var lis = $('ul.yes').find('li.js-select');
    var timeArry = [];
    var timePoit = [];
    var meetingId = $('ul.yes').data('id');
    var meetingName = $('ul.yes').data('name');
    $.each(lis, function(k, v) {
      if ($(v).attr('time')) {
        timeArry.push($(v).attr('time'));
        timePoit.push($(v).attr('timePoit'));
      }
    });

    var startDate = timeArry[0].split('-')[0];
    var endDate = timeArry[timeArry.length - 1].split('-')[1];

    $.ajax({
      url: '/qfang-weixin/qiye/meeting/add',
      data: { 'id': meetingId, 'mobile': $.config.mobile, 'useDate': useDate, 'dates': timePoit.join(',') },
      beforeSend: function() {
        determineBtn.prop('disabled', true);
        $.showPreloader();
      },

      success: function(data) {
        if (data.code == '1000') {
          setTimeout(function() {
            $.confirm('会议室已预定,现在去添加会议成员和会议主题？', function() {
              location.href = '/my-booking.html';
            }, function() {
              initReservedMeeting($.config.mobile, $('#floor').text().replace(/[^0-9]/ig, ''));
            });
          }, 500);
        } else {
          $.alert(data.msg, function() {
            initReservedMeeting($.config.mobile, $('#floor').text().replace(/[^0-9]/ig, ''));
          });

          determineBtn.prop('disabled', false);
        }
      },

      complete: function() {
        $.hidePreloader();
      }
    });
  });

  history.replaceState(null, null, 'index.html');
});
